package com.qfedu.empproject.controller;

import com.qfedu.empproject.entity.Emp;
import com.qfedu.empproject.entity.Manager;
import com.qfedu.empproject.service.EmpService;
import com.qfedu.empproject.service.ManagerService;
import com.qfedu.empproject.service.impl.EmpServiceImpl;
import com.qfedu.empproject.service.impl.ManagerServiceImpl;
import com.qfedu.empproject.utils.Page;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Objects;


@WebServlet("/login")
public class LoginController extends HttpServlet {

    private ManagerService managerService = new ManagerServiceImpl();
    private EmpService empService = new EmpServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取用户名和密码 进行登录
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        System.out.println("登录控制器:name=" + name + ",password:" + password);
        HttpSession session = req.getSession();
        // 从session中去除验证吗
        String codeStr = (String) session.getAttribute("code");
        // 校验验证码是否正确
        if(Objects.equals(code,codeStr)){
            // 调用service层的登录方法
            Manager login = managerService.login(name, password);
            // 如果登录失败重定向到登录页面 如果成功的话 进入到成功页面
            if (Objects.nonNull(login)) {
                // 转发到员工列表页面
                session.setAttribute("loginUser",login);
                // 得知道数据库总共多少条数据
                long totalCount = empService.getTotalCount();
                // 登录成功后查询所有员工数据，返回给员工列表页面
                Page page = new Page(1, 10);
                page.setTotalCount(Integer.valueOf(totalCount+""));
                List<Emp> empList = empService.getEmpsByPage(page);
                // 把查到的员工列表放入request中，下个页面就i可以获取到数据了
                req.setAttribute("empList",empList);
                req.setAttribute("page",page);
                req.getRequestDispatcher("/manager/showAllEmp.jsp").forward(req, resp);
            } else {
                // 重定向
                String path = req.getContextPath();
                resp.sendRedirect(path + "/index.jsp");
            }
        }else {
            // 验证吗输入错误
            String path = req.getContextPath();
            resp.sendRedirect(path + "/index.jsp");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
